import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/collection_model/collection_transfer_record_model.dart';
import 'package:yysk_app/model/tab_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/my_webview/my_webview_page.dart';
import 'package:yysk_app/pages/nft_pages/transfer_record/transfer_out_detail_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/widget/app_bar_back_widget.dart';
import 'package:yysk_app/widget/card_list_tile_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/item_card_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/refresh_and_scroll_widget.dart';
import 'package:yysk_app/widget/tab_widget.dart';

class CirculateRecordPage extends StatefulWidget {
  static const path = '/circulateRecordPage';
  const CirculateRecordPage({super.key});
  @override
  State<StatefulWidget> createState() => _CirculateRecordPage();
}

class _CirculateRecordPage extends State<CirculateRecordPage> {
  final ScrollController scrollController = ScrollController();
  final GlobalController globalController = Get.find();
  final list = RxList<CollectionTransferRecordItem>([]);
  int pageNum = 1;
  int pageSize = 10;
  bool purchase = true;

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getRecordList(loadMore: true);
      }
    });
    _getRecordList();
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  _getRecordList({loadMore = false}) {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    try {
      http.netFetch<CollectionTransferRecordModel>(
        ApiUrl.collectionTransferRecord,
        params: {'pageNum': pageNum, 'pageSize': 20, 'purchase': purchase},
        success: (result) {
          List<CollectionTransferRecordItem> items = result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            list.clear();
          }
          setState(() {
            list.addAll(items);
          });
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNum--;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;

    return Scaffold(
      body: Container(
        color: AppColors.backgroundColor,
        child: Column(
          children: [
            Expanded(
              child: Stack(
                children: [
                  SizedBox(
                    width: context.width,
                    child: ImageAssetWidget(
                      width: 375.px,
                      height: 196.px,
                      alignment: Alignment.topCenter,
                      imageUrl: 'static/images/prop_transfer_bg.png',
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                    child: Column(
                      children: [
                        SizedBox(height: top),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            AppBarBackWidget(
                              context: context,
                              onBack: () {},
                              backgroundColor: AppColors.backgroundColorBlack,
                            ),
                            Text(
                              '流转记录',
                              style: TextStyle(
                                fontSize: 18,
                                color: AppColors.fontColorBlack,
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                Get.toNamed(
                                  '${MyWebViewPage.path}?url=${globalController.staticInfo.value!.bsnChainUrl}',
                                  arguments: {
                                    'url':
                                        '${globalController.staticInfo.value!.bsnChainUrl}',
                                  },
                                );
                              },
                              child: Container(
                                width: 50.px,
                                height: 18.px,
                                margin: EdgeInsets.only(right: 16.px),
                                child: Text(
                                  '链上记录',
                                  style: TextStyle(
                                    fontSize: 12.px,
                                    color: AppColors.fontColorBlack,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 13.px),
                          child: TabWidget(
                            isCurrentFontSize: 14,
                            notCurrentFontSize: 14,
                            tabList: [
                              TabModel(label: '我接收的', code: 'true'),
                              TabModel(label: '我发送的', code: 'false'),
                            ],
                            onChanged: (val) {
                              setState(() {
                                purchase = val == 'true' ? true : false;
                              });
                              _getRecordList();
                            },
                          ),
                        ),
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.fromLTRB(12, 10, 12, 0),
                            child: RefreshAndScrollWidget(
                              onRefresh: _handleRefresh,
                              scrollController: scrollController,
                              itemBuilder: (item, index) => _listItem(item),
                              itemCount: list.length,
                              items: list,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _listItem(item) {
    return GestureDetector(
      onTap: () {
        Get.toNamed(
          '${MyWebViewPage.path}?url=${globalController.staticInfo.value!.bsnPublicChainUrl}${item.txHash}',
          arguments: {
            'url':
                '${globalController.staticInfo.value!.bsnPublicChainUrl}${item.txHash}',
          },
        );
      },
      child: Container(
        height: 208.px,
        margin: EdgeInsets.only(bottom: 12.px),
        decoration: BoxDecoration(
          color: AppColors.backgroundColorGreyF7,
          borderRadius: BorderRadius.circular(6.px),
        ),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.fromLTRB(8.px, 1.px, 8.px, 3.px),
              decoration: BoxDecoration(
                color: AppColors.backgroundColorGreyF2,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(6.px),
                  topRight: Radius.circular(6.px),
                ),
              ),
              height: 36.px,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  ImageAssetWidget(
                    width: 31.px,
                    height: 32.px,
                    // alignment: Alignment.topCenter,
                    imageUrl: 'static/images/change_ico.png',
                  ),
                  hiSpace(width: 3.px),
                  Text(
                    _buildTransferType(item),
                    style: TextStyle(
                      fontSize: 14,
                      color: AppColors.fontColorBlack,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(8.px, 11.px, 8.px, 3.px),
              child: Row(
                children: [
                  LazyImage(
                    imageUrl: '${item.coverImageUrl}',
                    height: 48.px,
                    width: 48.px,
                    borderRadius: 4.px,
                  ),
                  hiSpace(width: 11.px),
                  SizedBox(
                    height: 48.px,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 180.px,
                          child: Text(
                            '${item.collectionName}',
                            style: TextStyle(
                              fontSize: 14,
                              color: AppColors.backgroundColorBlack,
                              fontWeight: FontWeight.normal,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Stack(
                          children: [
                            ImageAssetWidget(
                              imageUrl: 'static/images/code_ico.png',
                              width: 18.px,
                              height: 18.px,
                            ),
                            Container(
                              height: 18.px,
                              // width: 84.px,
                              margin: EdgeInsets.only(left: 9.px),
                              padding: EdgeInsets.fromLTRB(9.px, 0, 4.px, 0),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.only(
                                  topRight: Radius.circular(8.px),
                                  bottomRight: Radius.circular(8.px),
                                ),
                                color: Colors.black.withOpacity(0.05),
                              ),
                              child: Text(
                                '编号 ${item.tokenId}',
                                style: TextStyle(
                                  fontSize: 12.px,
                                  color: const Color(0xFF3D3D3D),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 8.px),
              child: _buildDetail(item),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetail(item) {
    return ItemCardWidget(
      backgroundColor: AppColors.backgroundColorGreyF7,
      child: Column(
        children: [
          CardListTileWidget(
            label: '发送方',
            value: '${item.fromAddress ?? ''}',
            margin: EdgeInsets.only(top: 10.px),
          ),
          CardListTileWidget(
            label: '接收方',
            value: '${item.toAddress ?? ''}',
            margin: EdgeInsets.only(top: 10.px),
          ),
          CardListTileWidget(
            label: '流转时间',
            value: '${item.createTime ?? ''}',
            margin: EdgeInsets.only(top: 10.px),
          ),
        ],
      ),
    );
  }

  _buildTransferType(item) {
    switch (item.transferType) {
      case 'ACTIVITY':
        return '活动';
      case 'FIRST_PUBLISH':
        return '首发';
      case 'TRANSFER':
        return '转赠';
      case 'BLIND_BOX':
        return '心愿盒';
      case 'SYNTHESIS':
        return '合成';
      case 'DECOMPOSITION':
        return '分解';
      case 'AIRDROP':
        return '空投';
      case 'TRANSFER_EXTERNAL':
        return '外部转赠';
      case 'VERSATILE_MAGIC':
        return '魔坊';
      default:
        return '';
    }
  }

  Future<void> _handleRefresh() async {
    _getRecordList();
  }
}
